/*

 * Copyright (c) 2017-2018, FastDev 刘强 (fastdev@163.com).

 *

 * Licensed under the Apache License, Version 2.0 (the "License");

 * you may not use this file except in compliance with the License.

 * You may obtain a copy of the License at

 *

 *      http://www.apache.org/licenses/LICENSE-2.0

 *

 * Unless required by applicable law or agreed to in writing, software

 * distributed under the License is distributed on an "AS IS" BASIS,

 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.

 * See the License for the specific language governing permissions and

 * limitations under the License.

 */

package of.hotswapinject.agent;


import java.io.IOException;

import of.hotswapinject.app.Command;
import of.hotswapinject.core.common.ConfigUtil;
import com.sun.tools.attach.*;
import of.hotswapinject.core.common.Util;
import org.apache.commons.cli.CommandLine;

import java.lang.instrument.Instrumentation;
import java.util.List;
import java.util.jar.JarFile;

public class AgentAttach {
    public static void main(String[] args) throws AttachNotSupportedException,
            IOException, AgentLoadException, AgentInitializationException {
        attach(args[0], null);
    }

    public static void attach(String pid, String[] params) throws IOException, AgentLoadException, AgentInitializationException, AttachNotSupportedException {
        VirtualMachine vm = VirtualMachine.attach(pid);
        vm.loadAgent(JarFileHelper.getLocalJarPath(), String.join(Util.sep, params));
        vm.detach();
    }

    public static void agentmain(String args, Instrumentation inst) throws Exception {
        String jarPath = JarFileHelper.getLocalJarPath();
        inst.appendToBootstrapClassLoaderSearch(new JarFile(jarPath));
        ConfigUtil.init(jarPath);
        PluginInstallContext context = new PluginInstallContext();
        List<String> pluginPathList = context.init(jarPath);
        CommandLine cmd = Command.getCommandLine(context, args.split(Util.sep));
        context.onAttach(args, inst);
        try {
            new TransformerInstaller().install(context, cmd, inst);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}